import {defineStore, type StoreDefinition} from "pinia";
import type {TokenRequest} from "@/api/types";
import tokenApi from "@/api/token";
import {useUserStore} from "@/store/user";

type AppState = {
    token: string,
    menuCollapsed: boolean,
};

export const useAppStore = defineStore(
    "app",
    {
        state: (): AppState => {
            return {
                token: "",
                menuCollapsed: false,
            };
        },
        //persist: true, // 通过插件方式存储到localStore（默认）也可指定session
        persist: {
            storage: sessionStorage, // localStorage 或 sessionStorage
            key: 'appToken', // 自定义Storage存储的名称
        },
        actions: {
            async login(loginForm: TokenRequest): Promise<void> {
                this.token = (await tokenApi.createToken(loginForm)).token;
            },
            async logout(): Promise<void> {
                const userStore = useUserStore();
                this.token = "";
                userStore.$reset();
            }
        }
    }
);